// Copyright 2022 The kubegems.io Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package validate

import (
	"github.com/go-playground/validator/v10"
	"kubegems.io/kubegems/pkg/service/models"
)

func (v *Validator) ProjectStructLevelValidation(sl validator.StructLevel) {
	project := sl.Current().Interface().(models.Project)
	tmp := models.Project{}
	// 新创建的时候，同租户下项目名字不能重名
	if project.ID == 0 && len(project.ProjectName) > 0 {
		if e := v.db.First(&tmp, "project_name = ? and tenant_id = ?", project.ProjectName, project.TenantID).Error; e == nil {
			sl.ReportError(project.ProjectName, "项目名字", "ProjectName", "dbuniq", "项目")
		}
	}
	// 修改项目的时候，同租户下项目名字不能重名
	if project.ID != 0 {
		if e := v.db.First(&tmp, "project_name = ? and tenant_id = ? and id <> ?", project.ProjectName, project.TenantID, project.ID).Error; e == nil {
			sl.ReportError(project.ProjectName, "项目名字", "ProjectName", "dbuniq", "项目")
		}
	}
}
